package com.edu.framework.websocket.handler;

import cn.hutool.core.util.StrUtil;
import com.edu.framework.websocket.WebSocketHolder;
import com.edu.framework.websocket.message.base.Response;
import com.edu.framework.websocket.message.highlights.HighlightsRequest;
import com.edu.framework.websocket.message.notice.NoticeRequest;
import com.edu.framework.websocket.message.ping.PingRequest;
import com.edu.framework.websocket.service.NoticeService;
import com.edu.framework.websocket.service.PingService;
import java.io.IOException;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

@Component
public class PingRequestHandler implements IHandler<PingRequest> {

    @Resource
    private PingService wsPingService;

    @Override
    public void execute(WebSocketSession session, PingRequest message) {
        if (message == null) {
            return;
        }

        Map<String, String> data = message.getData();
        String ts = data.get("timestamp");

        Response response = Response.ok(PingRequest.TYPE, PingRequest.RESP_KEY, Long.parseLong(ts));
        try {
            wsPingService.handlePing(session, Long.parseLong(ts));
            WebSocketHolder.send(session, response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    @Override
    public String getType() {
        return PingRequest.TYPE;
    }
}
